<?php
/*
 * Copyright (c) 2021.  Liuhongbin All rights reserved.
 * @domain http://dkyx.cc
 * @author liuhongbin <514660094@qq.com>
 */

namespace hiduoke\services;

use app\common\model\addon\Addons;
use app\common\model\platform\PlatformAddon;
use app\common\model\system\Config;
use app\common\services\Upgrade;
use think\facade\Cache;

class CloudServer
{
    const INSTALL_PACKAGE = 0;
    const UPDATE_PACKAGE = 1;

    protected $api = '';
    protected $params = [];
    public $error = '';

    public function __construct()
    {
        $this->api = config('hiduoke.api_app') . '/cloud/';
    }

    protected function httpPost($path, $data)
    {
        $data = array_merge($data, $this->getParams());
        $res = httpPost($this->api . "/" . $path, $data);
        $res = json_decode($res, true);
        return $res;
    }

    private function getParams()
    {
        $cloud = Config::get("cloud");
        try {
            $params = array(
                'site_id' => $cloud['site_id'],
                'token'   => $cloud['token'],
                'domain'  => $cloud['domain'] ?: request()->server("SERVER_NAME")
            );
            return $params;
        } catch (\Exception $e) {
//            abort(-1, '云平台信息错误，请联系多客售后解决');
            return [];
        }
    }

    /**
     * 获取广告信息
     * @return mixed
     */
    public function getAdList($status, $count = 10)
    {
        return $this->httpPost("getAdList", [
            'status' => $status,
            'count'  => $count
        ]);
    }

    /**
     * 获取站点信息
     * @return mixed
     */
    public function getSite()
    {
//        $data = Cache::get('getSite');
//        if ($data) {
//            return $data;
//        } else {
//            $data = $this->httpPost("getSiteMsg", []);
//            Cache::set('getSite', $data);
//            return $data;
//        }
        return $this->httpPost("getSiteMsg", []);
    }

    /**
     * 获取登录用户信息
     * Create by :  刘泓宾<514660094@qq.com>
     * @param $account
     * @param $password
     * @return mixed
     */
    public function getTokenByLoginUser($account, $password)
    {
        return $this->httpPost("getTokenByLoginUser", ['account' => $account, 'password' => $password]);
    }

    /**
     * 获取站点信息
     * Create by :  刘泓宾<514660094@qq.com>
     * @param $bind_domain
     * @param $user_token
     * @return mixed
     */
    public function getSiteMsgByLoginUser($account, $password)
    {
        return $this->httpPost("getSiteMsgByLoginUser", [
            'account'     => $account,
            'password'    => $password,
            'version'     => (new  Upgrade())->getVersion()['version'],
            'bind_domain' => request()->domain()
        ]);
    }

    /**
     * 更新站点信息
     * @return mixed
     */
    public function updateSite()
    {
        $Config = new Config();
        $version = (new  Upgrade())->getVersion()['version'];
        $about = $Config->getValueByKey('about');
        $site = $Config->getValueByKey('site');
        $data = array(
            "title"          => $site['name'] ?? request()->domain(),
            "version"        => $version ?? '2.1.0',
            "corporate_name" => $about['corporate_name'] ?? "",
            "phone"          => $about['phone'] ?? "",
            "qq"             => $about['qq'] ?? "",
        );
        return $this->httpPost("updateSite", $data);
    }

    /**
     * 获取安装包
     * @param string $version
     * @param int $type
     * @return bool|mixed|string
     */
    public function getProgram($old_version = "", $version = "", $type = self::UPDATE_PACKAGE)
    {
        $data = array(
            "type"        => $type,
            "old_version" => $old_version,//当前版本
            "version"     => $version //指定版本
        );
        return $this->httpPost("getDownFileUrl", $data);
    }

    /**
     * 获取更新安装包
     * @param $version
     * @return bool|mixed|string
     */
    public function getUpdateProgram($version)
    {
        $data = array(
            "version" => $version //指定版本
        );
        return $this->httpPost("getUpdateProgram", $data);
    }

    /**
     * 获取应用包
     * @param string $addon 应用标识
     * @return bool|mixed|string
     */
    public function getAddon($addon_name)
    {
        $data = array(
            "addon_name" => $addon_name
        );
        return $this->httpPost("getAddonMsg", $data);
    }


    public function getAddonList($page, $size, $addon_names = [], $type = -1, $keyword = '')
    {
        $data = array(
            "type"        => $type,
            'page'        => $page,
            'size'        => $size,
            'keyword'     => $keyword,
            'addon_names' => $addon_names
        );
        return $this->httpPost('getAddonList', $data);
    }

    /***************************************小程序*************************************************/

    /**
     * 获取小程序更新包
     * @param $addon_name
     * @return mixed
     */
    public function getAddonApp($addon_name)
    {
        $data = array(
            "addon_name" => $addon_name
        );
        return $this->httpPost("getAddonAppMsg", $data);
    }

    /**
     * 获取小程序更新信息
     * @param $addon_name
     * @return mixed
     */
    public function getAddonAppUpdateMsg($addon_name)
    {
        $data = array(
            "addon_name" => $addon_name
        );
        return $this->httpPost("getAddonAppUpdateMsg", $data);
    }

    /**
     * @param $data
     * @return bool|string
     */
    public function updateAddonApp($data, $app_type)
    {
        $query = http_build_query($data); // 补全这里
        $api = config('hiduoke.min_api_app', "http://upload-min-app.dkyx.cc");
        if ($app_type == 'dy') {
            $path = '/douyin/upload';
            $res = httpGet($api . $path . "?" . $query);
            $res = json_decode($res, true) ?? ['code' => -1, 'msg' => '未知错误，请检查配置项'];
        } else if ($app_type == 'wx') {
            $path = '/weixin/upload';
            // 改成post
            $res = httpPost($api . $path, $data, true);
            $res = json_decode($res, true) ?? ['code' => -1, 'msg' => '未知错误，请检查配置项'];
        }
        return $res;
    }

    /**
     * 更新应用版本到云端
     * @param $addon_name
     * @param $version
     * @return mixed
     */
    public function updateSiteAddonVersion($addon_name, $version)
    {
        $data = array(
            "addon_name" => $addon_name,
            "version"    => $version
        );
        return $this->httpPost("updateSiteAddonVersion", $data);
    }

    public function updateUninstallTime($addon_name)
    {
        $data = array(
            "addon_name" => $addon_name,
        );
        return $this->httpPost("updateUninstallTime", $data);
    }

    /**
     * 获取应用包
     * @param string $addon 应用标识
     * @return bool|mixed|string
     */
    public function getAddonUpdateMsg($addon_name, $version = '')
    {
        $data = array(
            "addon_name" => $addon_name,
            'version'    => $version
        );
        return $this->httpPost("getAddonUpdateMsg", $data);
    }

    /**
     * 获取站点应用信息
     * @param string $addon 应用标识
     * @return bool|mixed|string
     */
    public function getSiteAddon($addon_name)
    {
        $data = array(
            "addon_name" => $addon_name
        );
        return $this->httpPost("getSiteAddon", $data);
    }

    public function getSiteAddons($addon_names = [])
    {
        $data = array(
            "addon_name" => $addon_names
        );
        return $this->httpPost("getSiteAddons", $data);
    }

    /**
     * 站点应用列表数组
     * @param $addon_names
     * @return bool|mixed|string
     */
    public function getSiteAddonsCount($addon_names = [])
    {
        $res = Cache::get('getSiteAddonsCount');
        if ($res) {
            return $res;
        } else {
            if (!$addon_names) {
                $addon_names = [];
                $addons = (new Addons())->field('name')->select()->toArray();
                foreach ($addons as $key => $value) {
                    $addon_names[] = $value['name'];
                }
            }
            $data = array(
                "addon_names" => $addon_names
            );
            $res = $this->httpPost("getSiteAddonsCount", $data);
            Cache::set("getSiteAddonsCount", $res);
            return $res;
        }
    }

    /**
     * 获取站点应用Token
     * @param string $addon 应用标识
     * @return bool|mixed|string
     */
    public function getSiteAddonToken($addon_name, $plaid, $is_min_app = false)
    {
        $data = array(
            "addon_name" => $addon_name,
            "plaid"      => $plaid,
            'is_min_app' => $is_min_app
        );
        return $this->httpPost("getSiteAddonToken", $data);
    }

    /**
     * 移除站点应用Token
     * @param $addon_name
     * @param $plaid
     */
    public function deleteSiteAddonToken($addon_name, $addon_token, $plaid)
    {
        return $this->httpPost('deleteSiteAddonToken', [
            "addon_name"  => $addon_name,
            "plaid"       => $plaid,
            'addon_token' => $addon_token,
        ]);
    }

    /**
     * 站点应用列表数组
     * @param $addon_names
     * @return bool|mixed|string
     */
    public function getSiteAddonTokenCount($cache = true)
    {
        if (!$cache) {
            Cache::delete('getSiteAddonTokenCount');
        }
        $res = Cache::get('getSiteAddonTokenCount');

        if ($res) {
            return $res;
        } else {
            $names = (new Addons())->getAddonNames();
            $data = array(
                'names' => $names
            );
            $res = $this->httpPost("getSiteAddonTokenCount", $data);
            $cloud_data = $res['data'] ?? [];
            Cache::set("getSiteAddonTokenCount", $cloud_data);
            return $cloud_data;
        }
    }


    /**
     * 获取版本列表
     * @param $addon_names
     * @return bool|mixed|string
     */
    public function getAddonsVersion($addon_names)
    {
        $data = array(
            'addon_names' => $addon_names
        );
        return $this->httpPost("getAddonsVersion", $data);
    }

    /**
     * 获取单个应用版本
     * @param $addon_names
     * @return bool|mixed|string
     */
    public function getAddonVersion($addon_name)
    {
        $data = array(
            'addon_name' => $addon_name
        );
        return $this->httpPost("getAddonVersion", $data);
    }

    public function setCloudStatus($status = null)
    {
        \think\facade\Cache::set('cloud-status', $status);
        return $status;
    }

    public function getCloudStatus()
    {
        $res = \think\facade\Cache::get('cloud-status');
        if ($res === false) {
            return false;
        } else {
            return true;
        }
    }

    /********************************************接口类************************************************/

//    /**
//     * 获取应用下的接口信息
//     * @param $addon_name
//     * @param $addon_token
//     * @param $api_id
//     * @return mixed
//     */
//    public function getAddonApiInfo($api_id, $addon_name = "", $addon_token = "")
//    {
//        $addon_name = $addon_name ?: get_addon();
//        $plaid = get_plaid();
//        $addon_token = $addon_token ?: (new PlatformAddon())->where(['plaid' => $plaid, 'addon_name' => $addon_name])->value('token');
//        $data = array(
//            'addon_name'  => $addon_name,
//            'addon_token' => $addon_token,
//            'api_id'      => $api_id
//        );
//        $res = $this->httpPost("getAddonApiInfo", $data);
//        return $res;
//    }


//    /**
//     * 获取应用下的接口地址【废弃】
//     * @param $addon_name
//     * @param $addon_token
//     * @param $api_id
//     * @return mixed
//     */
//    public function getAddonApiUrl($api_id, $addon_name = '', $addon_token = '')
//    {
//        $key = 'getAddonApiUrl_' . $addon_name . '_' . $addon_token . '_' . $api_id;
//        $url = Cache::get($key);
//        if (!$url) {
//            $url = $this->getAddonApiInfo($api_id, $addon_name, $addon_token)['data']['api_url'] ?? false;
//            Cache::set($key, $url);
//        }
//        return $url;
//    }

    /**
     * 获取云端接口信息
     * @param $api_id string 接口ID
     * @param $password string 接口密码
     * @return mixed
     */
    public function getApiInfo($api_id, $password = '')
    {
        $data = array(
            'api_id'   => $api_id,
            'password' => $password
        );
        $res = $this->httpPost("getApiInfo", $data);
        return $res;
    }

    /**
     * 获取云端接口信息
     * @param $api_mark string 接口标识
     * @param $password string 接口密码
     * @return mixed
     */
    public function getApiInfoByMark($api_mark, $password = '')
    {
        $data = array(
            'api_mark' => $api_mark,
            'password' => $password
        );
        $res = $this->httpPost("getApiInfo", $data);
        return $res;
    }

    /**
     * 获取云端接口地址
     * @param $api_id_mark string|int 接口ID或标识
     * @param $password string 接口密码
     * @param string|false $api_type 接口类型 addon 携带应用参数|site 携带平台参数|false 不携带参数
     * @return false|mixed|string
     */
    public function getApiUrl($api_id_mark, $password = '', $api_type = 'addon')
    {

        $key = 'getApiUrl_' . $api_id_mark . '_' . $password;
        $url = Cache::get($key);
        if (!$url || 1) {
            if (is_numeric($api_id_mark)) {
                $res = $this->getApiInfo($api_id_mark, $password);
            } else {
                $res = $this->getApiInfoByMark($api_id_mark, $password);
            }
            $url = $res['data']['api_url'] ?? false;
            if (!$url) {
                $this->error = $res['msg'];
                return false;
            }
            if ($api_type) {
                if ($api_type == 'addon') {
                    $query = [
                        'dk_type'     => 'addon',
                        'addon_name'  => get_addon(),
                        'addon_token' => get_addon_token(),
                    ];
                    // 在不确定url是否已经有参数的情况下，使用这种方式
                } else if ($api_type == 'site') {
                    $cloud = Config::get("cloud");
                    $query = [
                        'dk_type'    => 'site',
                        'site_id'    => $cloud['site_id'],
                        'site_token' => $cloud['token'],
                    ];
                }
                $url = strpos($url, '?') !== false ? $url . '&' . http_build_query($query) : $url . '?' . http_build_query($query);
            }
            Cache::set($key, $url);
        }
        return $url;
    }

    /**
     * 获取当前站点Token转换成APiToken
     * @param $pid
     * @return string
     */
    public function getSiteApiToken($pid)
    {
        $getParams = $this->getParams();
        return md5('api' . $getParams['site_id'] . '_' . $pid . $getParams['token']);
    }
}
